package photostock.model;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import java.util.Vector;

import javax.imageio.ImageIO;

import photostock.control.DBPool;
import photostock.control.ItemCache;

public class ItemFactory {
	
	public static Vector<Hashtable<String, Object>> initItem(String s) {
		return DBPool.getInstance().getResult(s);
	}

	public static Vector<ItemInfo> getChildrenInfos(UserItem item, String s) {
		Vector<Hashtable<String, Object>> dbRes =  DBPool.getInstance().getResult(s);
		Vector<ItemInfo> res = new Vector<ItemInfo>();
		for (Hashtable<String, Object> table : dbRes) {
			ItemInfo info = new ItemInfo(item.getChildrenFields(), table);
			if (info.exists()) res.add(info);
		}
		return res;
	}

	public static boolean recItem(String s) {
		return DBPool.getInstance().execute(s);
	}

	public static boolean updateItem(String s) {
		return DBPool.getInstance().execute(s);
	}

	public static boolean deleteItem(String s) {
		return DBPool.getInstance().execute(s);
	}
	
	public static void cache(UserItem item) {
		ItemCache.getInstance().addToCache(item);
	}

	public static void uncache(UserItem item) {
		ItemCache.getInstance().removeFromCache(item);
	}

	public static boolean isCached(UserItem item) {
		return ItemCache.getInstance().isInCache(item.getName()+item.getId());
	}

	public static boolean isCached(String s) {
		return ItemCache.getInstance().isInCache(s);
	}
	
	public static UserItem getCached(String s) {
		return ItemCache.getInstance().getFromCache(s);
	}

	public static BufferedImage getImage(UserItem item) {
		BufferedImage res = null;
		try {
			res = ImageIO.read(new File(item.getHardPath()));
		} catch (Exception e) {
			System.out.println(e.getClass().getName() + " : " + "Pb d'acquisition de l'image - " + item.getHardPath());
		}
		return res;
		
	}
	
    public static boolean isLoginValid(String s) {
    	return s.matches("[a-zA-Z_0-9]*");
    }

    public static boolean isPasswordValid(String s) {
    	return s.matches("[a-zA-Z_0-9]*");
    }

    public static boolean isMailValid(String s) {
    	return s.equals("") || s.matches("[a-zA-Z_0-9]*@[a-zA-Z_0-9]*.[a-zA-Z_0-9]*");
    }
    
    public static boolean isLoginTaken(String s) {
    	return DBPool.getInstance().getResult("SELECT * FROM user WHERE login='"+s+"'").size() != 0;
    }

	
}
